﻿using MediatR;
using WMS.API.Application.Command.InventoryManagement;
using WMS.Domain.Entities.InventoryManagement;
using WMS.ErrorCode;
using WMS.Interfactructure.Interfaces;

namespace WMS.API.Application.CommandHandlers.InventoryManagement
{
    /// <summary>
    /// 库存管理-查询库存出入库明细命令-grx
    /// </summary>
    public class QueryInandoutofStorageCommandHandler : IRequestHandler<QueryInandoutofStorageCommand, APIResult<APIPaging<InandoutofStorage>>>
    {
        private readonly IBaseRepository<InandoutofStorage> _inandoutofStorageRepository;

        public QueryInandoutofStorageCommandHandler(IBaseRepository<InandoutofStorage> inandoutofStorageRepository)
        {
            _inandoutofStorageRepository = inandoutofStorageRepository;
        }
        /// <summary>
        /// 库存出入库明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<APIPaging<InandoutofStorage>>> Handle(QueryInandoutofStorageCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<InandoutofStorage>> res=new APIResult<APIPaging<InandoutofStorage>>("查询库存出入库明细成功");

            res.Code = ResultCode.Success;
            var query = _inandoutofStorageRepository.GetAll();
            query=query.WhereIf(!string.IsNullOrEmpty(request.Team), x => x.Team == request.Team)
                       .WhereIf(!string.IsNullOrEmpty(request.Typeof), x => x.Typeof == request.Typeof)
                       .WhereIf(!string.IsNullOrEmpty(request.WarehouseName), x => x.WarehouseName == request.WarehouseName)
                       .WhereIf(request.CreateTime.HasValue, x => x.CreateTime >= request.CreateTime.Value)
                       .WhereIf(request.EndTime.HasValue, x => x.CreateTime <= request.EndTime.Value);
            var totalCount = query.Count();
            var items = query.OrderByDescending(x => x.Id)
                             .Skip((request.CurrentPage - 1) * request.PageSize)
                             .Take(request.PageSize)
                             .ToList();
            APIPaging<InandoutofStorage> page = new APIPaging<InandoutofStorage>();
            page.TotalCount= totalCount;
            page.PageData = items;
            res.Data = page;
            return Task.FromResult(res);
        }
    }
}
